<template>
  <a-modal v-model:open="open" title="编辑账号" @ok="handleOk" @cancel="handleCancel">
    <a-form ref="formRef" :model="formState" style="margin-top: 16px">
      <a-form-item label="账号" name="account" :rules="[{ required: true, message: '请输入账号' }]">
        <a-input v-model:value="formState.account" placeholder="请输入账号" />
      </a-form-item>
      <a-form-item label="密码" name="password" :rules="[{ required: true, message: '请输入密码' }]">
        <a-input v-model:value="formState.password" placeholder="请输入密码" />
      </a-form-item>
      <a-form-item label="用户" name="user_name" :rules="[{ required: true, message: '请输入用户' }]">
        <a-input v-model:value="formState.user_name" placeholder="请输入用户" />
      </a-form-item>
      <a-form-item label="角色" name="role_id" :rules="[{ required: true, message: '请选择角色' }]">
        <a-select v-model:value="formState.role_id" placeholder="请选择角色">
          <a-select-option v-for="item in roleList" :key="item.id" :value="item.id">{{ item.role_name }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { fetchChooseRoleList } from '@/api/system'
import { createOrUpdateUser } from '@/api/system'

const emits = defineEmits(['refresh'])

const open = ref(false)
const handleOk = () => {
  formRef.value.validate().then(async () => {
    const payload = {
      ...formState.value,
      user_id: formState.value.id,
    }
    await createOrUpdateUser(payload)
    emits('refresh')
    open.value = false
  })
}
const handleCancel = () => {
  Object.keys(formState.value).forEach(key => {
    formState.value[key] = undefined
  })
  open.value = false
}
const openModal = (record: any) => {
  if (record) {
    Object.keys(formState.value).forEach(key => {
      formState.value[key] = record[key]
    })
  }
  if (!roleList.value.length) getRoleList()
  open.value = true
}

const roleList = ref<any[]>([])
const getRoleList = async () => {
  const res = await fetchChooseRoleList({})
  roleList.value = res.data.data
}
const formRef = ref()
const formState = ref<any>({
  id: undefined,
  account: undefined,
  password: undefined,
  role_id: undefined,
  user_name: undefined
})

defineExpose({ openModal })
</script>

<style scoped lang="scss"></style>
